/**
 * 团队市场页面
 * author wim
 */
import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/team_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/order/OrderDetailPage.dart';
import 'package:panda/set/InviteFriend.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:popup_window/popup_window.dart';
import '../base/Constant.dart';

class DianPuYejiPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TeamMarketView();
  }
}

class TeamMarketView extends State<DianPuYejiPage> {
  String token = "";
  TabController mController;
  String totalNum = "";
  String avatar = "";
  EasyRefreshController _controller = EasyRefreshController();
  String name = "";
  String auth_code = "";
  String bank_id = "", time1 = "开始日期", time2 = "结束日期";
  List<String> dataList = new List();
  List<bool> bools = new List();
  int page = 1;
  String id = "";
  List<TeamListDataData> list1 = List();
  String total1 = "0", total2 = "0";
  String group_id = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value ?? "";
      getTeamList();
    });
    bools..add(false)..add(false)..add(false);
    dataList..add("零售")..add("直属")..add("平推");
  }

  getTeamList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page;
    if (bools[1]) {
      map['type'] = 1;
      map['status'] = 2;
    } else if (bools[0]) {
      map['type'] = 1;
      map['status'] = 3;
    } else if (bools[2]) {
      map['type'] = 2;
    }
    if (!time1.contains("开始")) {
      map['start'] = time1;
    }
    if (!time2.contains("结束")) {
      map['end'] = time2;
    }
    map['keywords'] = id;
    map['per'] = 10;
    map['sign_type'] = SignType.GET_TEAM;
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/User/getPerformance",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    print(response);
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      if (page == 1) {
        _controller.finishRefresh();
        _controller.resetLoadState();
        list1.clear();
      } else {
        _controller.finishLoad();
      }
      TeamListEntity homeListEntity = new TeamListEntity.fromJson(userMap);
      list1.addAll(homeListEntity.data.datas);
      total1 = userMap['data']['allprice'].toString();
      total2 = userMap['data']['num'].toString();
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Scaffold(
        appBar: AppBar(
          title: Text('店铺业绩',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                  color: black)),
          elevation: 0.5,
          backgroundColor: white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
        ),
        body: Container(
          color: divideColor,
          width: double.infinity,
          child: new Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(10),
                color: white,
                child: Row(
                  children: <Widget>[
                    GestureDetector(
                      child: Center(),
                      behavior: HitTestBehavior.opaque,
                      onTap: () {},
                    ),
                    Expanded(
                      flex: 1,
                      child: Container(
                        margin: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(DP_10),
                            0,
                            ScreenUtil.getInstance().setHeight(DP_10),
                            0),
                        height: ScreenUtil.getInstance().setHeight(DP_60),
                        decoration: BoxDecoration(
                            color: f0Color,
                            borderRadius: BorderRadius.circular(20.0)),
                        child: ConstrainedBox(
                          constraints: BoxConstraints(maxHeight: DP_30),
                          child: TextField(
                            keyboardAppearance: Brightness.light,
                            maxLines: 1,
                            onChanged: (value) {
                              id = value;
                            },
                            textInputAction: TextInputAction.search,
                            onEditingComplete: () {
                              if (id.trim() == "") {
                                Fluttertoast.showToast(msg: "请输入搜索内容");
                                return;
                              }
                              page = 1;
                              _controller.callRefresh();
                            },
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)),
                            cursorColor: mainColor,
                            decoration: new InputDecoration(
                                prefixIcon: Icon(
                                  Icons.search,
                                  color: Colors.black45,
                                ),
                                hintText: "搜索订单号/商品名称/会员ID/微信名",
                                border: InputBorder.none,
                                hintStyle: TextStyle(
                                    color: Colors.black45,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                          padding: EdgeInsets.fromLTRB(8, 3, 8, 3),
                          decoration: BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.circular(10)),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(100),
                          child: Text('搜索',
                              style: TextStyle(
                                  color: white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE)))),
                      onTap: () {
                        if (id.trim() == "") {
                          Fluttertoast.showToast(msg: "请输入搜索内容");
                          return;
                        }
                        page = 1;
                        _controller.callRefresh();
                        // loadList();
                      },
                    )
                  ],
                ),
              ),
              Divider(height: 1),
              PopupWindowButton(
                offset: Offset(40, 200),
                child: Container(
                  padding: EdgeInsets.all(10),
                  color: white,
                  child: Row(
                    children: <Widget>[
                      Text(" 共",
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil.getInstance().setSp(22))),
                      Text("$total2",
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance().setSp(28))),
                      Text("个订单,合计",
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil.getInstance().setSp(22))),
                      Expanded(
                        child: Text("$MONEY$total1",
                            style: TextStyle(
                                color: mainColor,
                                fontSize: ScreenUtil.getInstance().setSp(30))),
                      ),
                      Text("筛选",
                          style: TextStyle(
                              color: Colors.grey,
                              fontSize: ScreenUtil.getInstance().setSp(22))),
                      Icon(
                        Icons.sort,
                        size: 20,
                        color: Colors.grey,
                      ),
                    ],
                  ),
                ),
                window: StatefulBuilder(
                  builder: (BuildContext context,
                      void Function(void Function()) setState) {
                    return Container(
                      padding: EdgeInsets.all(10),
                      alignment: Alignment.centerLeft,
                      color: white,
                      height: 225,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('业绩类型',
                              style: TextStyle(
                                  color: black,
                                  fontSize:
                                      ScreenUtil.getInstance().setSp(30))),
                          Container(
                            height: 5,
                          ),
                          Wrap(
                            spacing: ScreenUtil.getInstance()
                                .setHeight(0), //主轴上子控件的间距
                            runSpacing: ScreenUtil.getInstance()
                                .setHeight(0), //交叉轴上子控件之间的间距
                            children:
                                creatScope(dataList, setState), //要显示的子控件集合
                          ),
                          Container(
                            height: 5,
                          ),
                          Text('时间',
                              style: TextStyle(
                                  color: black,
                                  fontSize:
                                      ScreenUtil.getInstance().setSp(30))),
                          Container(
                            color: white,
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(DP_20)),
                            child: Row(
                              children: <Widget>[
                                Expanded(child: Center()),
                                GestureDetector(
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                                    decoration: BoxDecoration(
                                        border: Border.all(
                                            color: black_99, width: 1),
                                        borderRadius: BorderRadius.circular(3)),
                                    child: Row(children: <Widget>[
                                      Text('$time1',
                                          style: TextStyle(
                                              color: black_99,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE + 3))),
                                      Icon(
                                        Icons.arrow_drop_down,
                                        color: black_99,
                                      )
                                    ]),
                                  ),
                                  onTap: () {
                                    DatePicker.showDatePicker(context,
                                        pickerTheme: DateTimePickerTheme(
                                          showTitle: true,
                                          confirm: Text('确定',
                                              style:
                                                  TextStyle(color: Colors.red)),
                                          cancel: Text('取消',
                                              style: TextStyle(
                                                  color: Colors.cyan)),
                                        ),
                                        minDateTime:
                                            DateTime.parse("1980-05-01"),
                                        dateFormat: "yyyy-MM-dd",
                                        pickerMode: DateTimePickerMode.date,
                                        locale: DateTimePickerLocale.zh_cn,
                                        onCancel: () {
                                      debugPrint("onCancel");
                                    }, onConfirm: (dateTime, List<int> index) {
                                      setState(() {
                                        time1 = DateUtils.instance
                                            .getFormartData(
                                                timeSamp: dateTime
                                                    .millisecondsSinceEpoch,
                                                format: "yyyy-MM-dd");
                                        // page = 1;
                                        // loadList();
                                      });
                                    });
                                  },
                                ),
                                Expanded(child: Center()),
                                Text('  至  ',
                                    style: TextStyle(
                                        color: black,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE))),
                                Expanded(child: Center()),
                                GestureDetector(
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                                    decoration: BoxDecoration(
                                        border: Border.all(
                                            color: black_99, width: 1),
                                        borderRadius: BorderRadius.circular(3)),
                                    child: Row(children: <Widget>[
                                      Text('$time2',
                                          style: TextStyle(
                                              color: black_99,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(SMALL_FONT_SIZE + 3))),
                                      Icon(
                                        Icons.arrow_drop_down,
                                        color: black_99,
                                      )
                                    ]),
                                  ),
                                  onTap: () {
                                    DatePicker.showDatePicker(context,
                                        pickerTheme: DateTimePickerTheme(
                                          showTitle: true,
                                          confirm: Text('确定',
                                              style:
                                                  TextStyle(color: Colors.red)),
                                          cancel: Text('取消',
                                              style: TextStyle(
                                                  color: Colors.cyan)),
                                        ),
                                        minDateTime:
                                            DateTime.parse("1980-05-01"),
                                        dateFormat: "yyyy-MM-dd",
                                        pickerMode: DateTimePickerMode.date,
                                        locale: DateTimePickerLocale.zh_cn,
                                        onCancel: () {
                                      debugPrint("onCancel");
                                    }, onConfirm: (dateTime, List<int> index) {
                                      setState(() {
                                        time2 = DateUtils.instance
                                            .getFormartData(
                                                timeSamp: dateTime
                                                    .millisecondsSinceEpoch,
                                                format: "yyyy-MM-dd");
                                        // page = 1;
                                        // loadList();
                                      });
                                    });
                                  },
                                ),
                                Expanded(child: Center()),
                              ],
                            ),
                          ),
                          Expanded(child: Center()),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.all(4),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      color: Colors.grey,
                                      borderRadius: BorderRadius.circular(20)),
                                  width: 100,
                                  child: Text(
                                    '重置',
                                    style: TextStyle(color: white),
                                  ),
                                ),
                                onTap: () {
                                  for (int i = 0; i < bools.length; i++) {
                                    bools[i] = false;
                                  }
                                  group_id = "";
                                  time1 = "开始日期";
                                  time2 = "结束日期";
                                  Navigator.of(context).pop(1);
                                  page = 1;
                                  getTeamList();
                                },
                              ),
                              GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.all(4),
                                  margin: EdgeInsets.only(left: 20),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      color: mainColor,
                                      borderRadius: BorderRadius.circular(20)),
                                  width: 100,
                                  child: Text(
                                    '确定',
                                    style: TextStyle(color: white),
                                  ),
                                ),
                                onTap: () {
                                  Navigator.of(context).pop(1);
                                  page = 1;
                                  getTeamList();
                                },
                              )
                            ],
                          ),
                          Expanded(child: Center()),
                        ],
                      ),
                    );
                  },
                ),
              ),
              Container(
                height: 10,
              ),
              Expanded(
                child: new EasyRefresh(
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  controller: _controller,
                  child: ListView.separated(
                      itemBuilder: _renderRow,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container(
                          color: divideColor,
                          height: 5,
                        );
                      },
                      itemCount: list1.length),
                  onRefresh: () async {
                    page = 1;
                    getTeamList();
                  },
                  onLoad: () async {
                    page++;
                    getTeamList();
                  },
                ),
              ),
            ],
          ),
        ));
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: Column(
          children: <Widget>[
            Row(children: <Widget>[
              ClipOval(
                child: list1[index].avatar == null || list1[index].avatar == ""
                    ? Image.asset(
                        "images/app_icon.png",
                        fit: BoxFit.cover,
                        width: ScreenUtil.getInstance().setWidth(60),
                        height: ScreenUtil.getInstance().setWidth(60),
                      )
                    : CachedNetworkImage(
                        imageUrl: list1[index].avatar,
                        fit: BoxFit.cover,
                        width: ScreenUtil.getInstance().setWidth(60),
                        height: ScreenUtil.getInstance().setWidth(60),
                      ),
              ),
              Container(width: 8),
              Expanded(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  new Text(
                    list1[index].nickname + "  会员ID:" + list1[index].user_id,
                    style: new TextStyle(
                        color: Colors.black,
                        fontSize: ScreenUtil.getInstance().setSp(24)),
                  ),
                  // new Text(
                  //       '所属店铺:  '+list1[index].referrer_name,
                  //       style: new TextStyle(
                  //           color: Colors.black54,
                  //           fontSize: ScreenUtil.getInstance().setSp(24)),
                  //     ),
                ],
              )),
              new Text(
                list1[index].status_zh,
                style: new TextStyle(
                    color: mainColor,
                    fontSize: ScreenUtil.getInstance().setSp(24)),
              )
            ]),
            Container(height: 8),
            Divider(height: 1),
            Container(height: 8),
            Row(
              children: <Widget>[
                ClipRRect(
                  child: list1[index].img == null || list1[index].img == ""
                      ? Image.asset(
                          "images/app_icon.png",
                          fit: BoxFit.cover,
                          width: ScreenUtil.getInstance().setWidth(140),
                          height: ScreenUtil.getInstance().setWidth(140),
                        )
                      : CachedNetworkImage(
                          errorWidget: (context, url, error) {
                            return Image.asset("images/app_icon.png");
                          },
                          imageUrl: list1[index].img.contains("http")
                              ? list1[index].img
                              : Api.ImgBaseUrl + list1[index].img,
                          fit: BoxFit.cover,
                          width: ScreenUtil.getInstance().setWidth(140),
                          height: ScreenUtil.getInstance().setWidth(140),
                        ),
                ),
                Container(
                  width: 10,
                ),
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: new Text(
                            "订单号: " + list1[index].order_num,
                            style: new TextStyle(
                                color: Colors.black87,
                                fontSize: ScreenUtil.getInstance().setSp(26)),
                          ),
                        ),
                        new Text(
                          MONEY + list1[index].allprice,
                          style: new TextStyle(
                              color: Colors.black,
                              fontSize: ScreenUtil.getInstance().setSp(26)),
                        ),
                      ],
                    ),
                    Container(
                      height: 5,
                    ),
                    new Text(
                      list1[index].title,
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil.getInstance().setSp(24)),
                    ),
                    Container(
                      height: 4,
                    ),
                    new Text(
                      "共" + list1[index].num + "件",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize: ScreenUtil.getInstance().setSp(23)),
                    ),
                    Container(
                      height: 4,
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                            child: new Text(
                          list1[index].create_time,
                          style: new TextStyle(
                              color: Colors.black54,
                              fontSize: ScreenUtil.getInstance().setSp(23)),
                        )),
                        new Text(
                          "收入:" + list1[index].amount,
                          style: new TextStyle(
                              color: Colors.black54,
                              fontSize: ScreenUtil.getInstance().setSp(23)),
                        ),
                      ],
                    ),
                  ],
                ))
              ],
            )
          ],
        ),
      ),
      onTap: () {
        if (list1[index].group_id == '1')
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return new OrderDetailPage(order_id: list1[index].id, type: '1');
          }));
      },
      behavior: HitTestBehavior.opaque,
    );
  }

  creatScope(List<String> dataList, setState) {
    var result = new List<Widget>();
    for (int i = 0; i < dataList.length; i++) {
      result.add(new GestureDetector(
        onTap: () {
          for (int n = 0; n < dataList.length; n++) {
            if (i != n) {
              bools[n] = false;
            } else {
              bools[i] = !bools[i];
              if (bools[i]) {
                group_id = (i + 1).toString();
              } else {
                group_id = "";
              }
            }
          }
          setState(() {});
        },
        child: new Container(
          width: 60,
          margin: EdgeInsets.all(4),
          padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(5)),
          child: new Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(5)),
            decoration: BoxDecoration(
                color: bools[i] ? mainColor : Colors.grey,
                borderRadius: BorderRadius.circular(5),
                border:
                    Border.all(color: bools[i] ? mainColor : white, width: 1)),
            child: Column(
              children: <Widget>[
                Text(
                  dataList[i],
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(BIG_FONT_SIZE - 5),
                      color: white),
                ),
              ],
            ),
          ),
        ),
      ));
    }
    return result;
  }
}
